﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using IPR_StudyMeetingMrgSys.ViewModel;
using IPR_StudyMeetingMrgSys.Models;
using IPR_StudyMeetingMrgSys.Enums;
using IPR_StudyMeetingMrgSys.Extension;
using IPR_StudyMeetingMrgSys.BLL;
using IPR_StudyMeetingMrgSys.Model;
using Newtonsoft.Json;
using log4net;
using System.Reflection;
using System.Data;

namespace IPR_StudyMeetingMrgSys.Controllers
{
    /// <summary>
    /// 授课内容包含培训内容的管理（增删改查）
    /// </summary>
    public class TrainContentController : ApiController
    {

        ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);


        // POST: api/TrainContent
        /// <summary>
        /// 添加授课内容及培训内容，如果授课内容对应的计划名称已经存在，那么就是更新授课内容
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/TrainContent/Add")]
        public IHttpActionResult Add(ViewModel.VM_TrainContent model)
        {
            //string sResult = "";
            log.Info(JsonConvert.SerializeObject(model));

            Model.TrainContent mTrainContent = new Model.TrainContent();
            ResultMsg resultMsg = new ResultMsg();
            try
            {
                mTrainContent.TPID = model.TPID;
                mTrainContent.TCID=new BLL.SysManage().GetMaxId("TrainContent", "TCID");
                mTrainContent.TContent = model.TContent;
 
                //mTrainContent.TPDesignUserID = LoginUser.UserInfo.UserID;//model.TPDesignUserID;
                //mTrainContent.TPDesignUserName = LoginUser.UserInfo.UserName;  //model.TPDesignUserName;
                mTrainContent.TCDepID = LoginUser.DepID;// model.TPDepID;
                mTrainContent.AddUserID = LoginUser.UserInfo.UserID;
                mTrainContent.AddUserName = LoginUser.UserInfo.UserName;
                mTrainContent.AddDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                mTrainContent.TCDepLevel =LoginUser.DepLevel;
                mTrainContent.IsUse = 1;
                mTrainContent.IsCheck = 0;
                mTrainContent.IsRelease = 0;
                mTrainContent.TCSendDepID = model.TCSendDepID??LoginUser.DepID.ToString();
                 
                BLL.TrainContent bllTrainContent = new BLL.TrainContent();
                if (!bllTrainContent.Exists(model.TContent))
                {
                    //授课内容不存在，添加新的授课内容 
                    bllTrainContent.Add(mTrainContent);
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                    resultMsg.Count = 1;
                    resultMsg.Data = "授课内容增加成功！";
                }
                else
                {

                    //授课内容已经存在,获取授课内容对应的ID，此时是更新授课内容及授课内容的内容 
                    resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                    resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                    resultMsg.Data = "授课内容名称已经存在，请不要重复！";
                }
            }
            catch (Exception exc)
            {

                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = "授课内容增加异常！" + exc.Message;
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 试卷查询
        /// </summary>
        /// <param name="swhere">查询条件</param>
        /// <param name="page">页索引</param>
        /// <param name="limit">页大小</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/TrainContent/Search")]
        public IHttpActionResult Search(string swhere, int page, int limit)
        {
            ResultMsg resultMsg = new ResultMsg();
            try
            {
                swhere = swhere ?? string.Empty;
                int startindex = (page - 1) * limit + 1;
                int endindex = page * limit;
                if (!string.IsNullOrWhiteSpace(swhere))
                {
                    Dictionary<string, string> jsonObject = JsonConvert.DeserializeObject<Dictionary<string, string>>(swhere);
                    swhere = " 1=1 ";
                    foreach (var item in jsonObject)
                    {
                        if (item.Key == "TContent")
                        {if((item.Value!="")&&(item.Value!=null))
                            swhere += $" AND TContent like '%{item.Value}%' ";
                        }
                        //if (item.Key == "TPReleaseStart")
                        //{
                        //    if ((item.Value != "") && (item.Value != null))
                        //        swhere += $" AND TPReleaseStart >= convert(varchar(20),'{item.Value}',120) ";
                        //}
                        //if (item.Key == "TPReleaseEnd")
                        //{
                        //    if ((item.Value != "") && (item.Value != null))
                        //        swhere += $" AND TPReleaseEnd <= convert(varchar(20),'{item.Value}',120) ";
                        //}
                        if (item.Key == "IsCheck")
                        {
                            if ((item.Value != "") && (item.Value != null))
                                swhere += $" AND IsCheck ={item.Value} ";
                        }
                        if (item.Key == "IsRelease")
                        {
                            if ((item.Value != "") && (item.Value != null))
                                swhere += $" AND IsRelease ={item.Value} ";
                        }
                        if (item.Key == "IsUse")
                        {
                            if ((item.Value != "") && (item.Value != null))
                                swhere += $" AND IsUse ={item.Value} ";
                        }
                        if (item.Key == "TCDepPLevel")
                        {
                            ///选择页
                            if ((item.Value != "") && (item.Value != null))
                                swhere += $" AND TCDepLevel=" + LoginUser.DepPLevel + "";
                            swhere += $" and  IsRelease='1' and IsCheck='1' ";
                        }
                        //if (item.Key== "TPDepLevel")
                        //{
                        //    if ((item.Value != "") && (item.Value != null))
                        //        swhere += $" AND TPDepLevel<="+LoginUser.DepLevel+"";
                        //}
                        //if (item.Key== "TPDepID") {
                        //    if ((item.Value != "") && (item.Value != null))
                        //        swhere += $" AND TPDepID="+LoginUser.DepID+"+";
                        //}
                        if (item.Key== "self")
                        {
                            //区别:self：1 筛选子级部门的，上级部门的则是 已审核 已发布的
                            if ((item.Value != "") && (item.Value != null))
                            {
                                switch (item.Value)
                                {
                                    case "0"://列表页 ,当前部门,上级部门,审核，发布
                                      
                                        //swhere += $" or ( TCDepLevel=" + LoginUser.DepLevel + " AND TCDepID=" + LoginUser.DepID + " )";
                                        
                                        // swhere += $" OR (TCSendDepID like '" + LoginUser.DepID.ToString() + "%' or TCSendDepID like '" + LoginUser.DepID.ToString() + ",%' or TCSendDepID like '," + LoginUser.DepID.ToString() + "%' ) ";
                                        switch (LoginUser.DepLevel)
                                        {
                                            case 0:
                                                #region 段读取所有计划信息[状态为 已发布,已审核]
                                                //级别数字 大于本 级别数字  即：下级 的  审核并发布的 计划
                                                //本级别的 所有计划
                                                swhere += $" AND ( TCDepLevel<" + LoginUser.DepLevel + " and IsRelease='1' and IsCheck='1')";
                                                swhere += $" or ( TCDepLevel=" + LoginUser.DepLevel + " AND TCDepID=" + LoginUser.DepID + ")";
                                                #endregion
                                                break;
                                            default:
                                                //下发给当前部门的计划
                                                //本部门创建的计划
                                                swhere += " and CHARINDEX('"+LoginUser.DepID+ "',TCSendDepID,0)>0 and IsRelease='1' and IsCheck='1' ";
                                                swhere += $" or ( TCDepLevel=" + LoginUser.DepLevel + " AND TCDepID=" + LoginUser.DepID + ")";
                                                break;
                                        }

                                        break;
                                    case "1"://筛选页 [筛选发给本部门的   和本部门 已审核的]
                                        //swhere += $" AND ( TCDepLevel<" + LoginUser.DepLevel + " and IsRelease='1' and IsCheck='1')";
                                        swhere += " and CHARINDEX('" + LoginUser.DepID + "',TCSendDepID,0)>0 and IsRelease='1' and IsCheck='1' ";
                                        swhere += $" or (TCDepID=" + LoginUser.DepID + " and IsRelease='1' and IsCheck='1')";
                                        break;
                                    case "2"://筛选页 [筛选本部门计划  如：授课内容 筛选培训计划]
                                        swhere += $" AND ( TCDepID=" + LoginUser.DepID + " and IsRelease='1' and IsCheck='1')";
                                        break;
                                }

                            }
                        }
                    }
                }

                bool blExist = false;
                int rowCount = 0;
                DataSet dsSearch = new IPR_StudyMeetingMrgSys.BLL.TrainContent().GetListByPage(swhere, "TCID", startindex, endindex,out rowCount);
                if (dsSearch != null)
                    if (dsSearch.Tables.Count > 0)
                        if (dsSearch.Tables[0].Rows.Count > 0)
                        {
                            //返回token信息
                            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                            resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                            resultMsg.Data = dsSearch.Tables[0];
                            resultMsg.Count = rowCount;
                            blExist = true;
                        }
                if (!blExist)
                {
                    //返回token信息
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = "查询结果不存在";
                    resultMsg.Data = null;
                }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText()+exc.Message;
                resultMsg.Data = "查询异常！" + exc.Message;
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 授课内容编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/TrainContent/Edit")]
        public IHttpActionResult Edit(Model.TrainContent model)
        {
            log.Info(JsonConvert.SerializeObject(model));
            model.AddUserID = LoginUser.UserInfo.UserID;
            model.AddUserName = LoginUser.UserInfo.UserName;
            model.AddDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            if (string.IsNullOrEmpty(model.TCSendDepID))
            {
                model.TCSendDepID = LoginUser.DepID.ToString();
            }
            ResultMsg resultMsg = new ResultMsg();
            try
            {
                string errorMsg = string.Empty;
                if (new IPR_StudyMeetingMrgSys.BLL.TrainContent().Update(model,out errorMsg))
                {
                    resultMsg.Info = "编辑成功";
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Count = 1;
                    
                }
                else
                {
                    resultMsg.Info = errorMsg;
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 授课内容删除(根据人员工号)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/TrainContent/Del")]
        public IHttpActionResult Del(Model.TrainContent model)
        {
            log.Info(JsonConvert.SerializeObject(model));

            ResultMsg resultMsg = new ResultMsg();
            try
            {
                    if (new IPR_StudyMeetingMrgSys.BLL.TrainContent().Delete(model.TCID))
                    {
                        resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                        resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                        resultMsg.Data = "授课内容删除成功！";
                    }
                    else
                    {
                        resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                        resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                        resultMsg.Data = "授课内容删除失败！";
                    }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                resultMsg.Data = "授课内容删除时出现异常！" + exc.Message;
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 授课内容信息删除(根据文件工号)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/TrainContent/DelList")]
        public IHttpActionResult DelList(string delidlist)
        {
            log.Info(JsonConvert.SerializeObject(delidlist));

            ResultMsg resultMsg = new ResultMsg();
            try
            {
                if (new IPR_StudyMeetingMrgSys.BLL.TrainContent().DeleteList(delidlist))
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                    resultMsg.Data = "授课内容删除成功！";
                }
                else
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = "删除成功，删除0行"; 
                }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = "文件信息删除时出现异常！" + exc.Message;
            }
            return Json(resultMsg);
        }
        /// <summary>
        /// 授课内容发布
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/TrainContent/Release")]
        public IHttpActionResult ReleaseList(string TPIDlist)
        {
            log.Info(JsonConvert.SerializeObject(TPIDlist));

            ResultMsg resultMsg = new ResultMsg();
            try
            {
                if (new IPR_StudyMeetingMrgSys.BLL.TrainContent().Release(TPIDlist))
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                    resultMsg.Data = "授课内容删除成功！";
                }
                else
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = "删除成功，删除0行";
                }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = "文件信息删除时出现异常！" + exc.Message;
            }
            return Json(resultMsg);
        }
        /// <summary>
        /// 授课内容信息删除(根据文件工号)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/TrainContent/GetSingle")]
        public IHttpActionResult GetSingle(string TCID)
        {
            log.Info(JsonConvert.SerializeObject(TCID));

            ResultMsg resultMsg = new ResultMsg();
            try
            {
                Model.TrainContent mTP = new IPR_StudyMeetingMrgSys.BLL.TrainContent().GetModel( Int32.Parse(TCID));
                if (mTP!=null&&mTP.TPID!=0)
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                    resultMsg.Data = mTP;
                }
                else
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                    resultMsg.Info = "数据不存在！";
                }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = "内部请求出错 " + exc.Message;
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 更新计划的状态，包含(审核、取消审核、发布、取消发布、使用、未使用)
        /// value 为0时表示取消审核/发布/使用中，为1时表未取消审核/取消发布/未使用
        /// </summary>
        /// <param name="mark">标记码，审核：C / 发布：R / 使用：U</param>
        /// <param name="value">1/0</param>
        /// <param name="wherevalue">条件，使用主键字段值 </param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/TrainContent/UpdatePlanStatus")]
        public IHttpActionResult UpdatePlanStatus(string mark, string value, string wherevalue)
        {
            log.Info(JsonConvert.SerializeObject(mark + "=" + value));

            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                string tablename = "TrainContent";
                string fieldname = "";
                string fieldvalue = "";
                string wherefield = "TCID";
                if (mark == "C")
                {
                    fieldname = "IsCheck";
                }
                if (mark == "R")
                {
                    fieldname = "IsRelease";
                }
                if (mark == "U")
                {
                    fieldname = "IsUse";
                }
                fieldvalue = value;
                string ErrorMsg = string.Empty;
                new BLL.SysManage().ExecuteUpdate(tablename, fieldname, fieldvalue, wherefield, wherevalue, out ErrorMsg);
                if (string.IsNullOrEmpty(ErrorMsg))
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = "更新成功";
                    resultMsg.Count = 1;
                }
                else
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                    resultMsg.Info = ErrorMsg;
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }
        // GET: api/TrainContent
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/TrainContent/5
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/TrainContent
        public void Post([FromBody]string value)
        {
        }

        // PUT: api/TrainContent/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/TrainContent/5
        public void Delete(int id)
        {
        }
    }
}
